package com.dai.zhenfujin;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.dai.zhenfujin.Constants.Constants;
import com.dai.zhenfujin.Constants.EventConstants;
import com.dai.zhenfujin.addresslist.AddressListFragment;
import com.dai.zhenfujin.addresslist.fragment.ConversationListFragment;
import com.dai.zhenfujin.base.BaseActivity;
import com.dai.zhenfujin.bean.FollowBean;
import com.dai.zhenfujin.bean.MessageEvent;
import com.dai.zhenfujin.bean.UserBean;
import com.dai.zhenfujin.http.CallBack;
import com.dai.zhenfujin.http.HttpClient;
import com.dai.zhenfujin.issue.activity.AlumIssueActivity2;
import com.dai.zhenfujin.my.MyFragment;
import com.dai.zhenfujin.my.activity.AlumTypeActivity;
import com.dai.zhenfujin.my.activity.MyActivity;
import com.dai.zhenfujin.my.activity.ReleaseActivity;
import com.dai.zhenfujin.my.activity.wallet.TopUpActivity;
import com.dai.zhenfujin.receiver.HMSPushHelper;
import com.dai.zhenfujin.utils.SPUtils;
import com.dai.zhenfujin.utils.UIUtils;
import com.dai.zhenfujin.view.BadgeView;
import com.dai.zhenfujin.view.CommonDialog;
import com.dai.zhenfujin.visitingcard.VisitingcardFragment;
import com.dai.zhenfujin.visitingcard.app.ParticularsPageActivity;
import com.hyphenate.EMClientListener;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.push.EMPushConfig;
import com.hyphenate.push.EMPushHelper;
import com.hyphenate.push.EMPushType;
import com.hyphenate.push.PushListener;
import com.hyphenate.util.EMLog;
import com.jaeger.library.StatusBarUtil;
import com.orhanobut.logger.Logger;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.dai.zhenfujin.Constants.EventConstants.PUBLISH_DYNAMIC;

public class MainActivity extends BaseActivity implements AMapLocationListener, View.OnClickListener {
    private FrameLayout frameLayout;
    private RadioGroup radioGroup;
    private RadioButton raButton;
    private List<Fragment> baseFragments;
    private int position;
    private Fragment mContent;
    //声明mlocationClient对象
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    public double latitude;
    public double longitude; //经度
    public String city;
    public static MainActivity mContext;
    private Button button2;
    private ImageView cv_img;
    private LinearLayout ll_fabu;
    private TextView unread_msg_number;
    private BadgeView badge1;
    public static List<FollowBean.FollowListBean> followList = new ArrayList<>();
    private PopupWindow mPopWindow;
    public static UserBean userBean;
    private Dialog dialog;
    private VisitingcardFragment visitingcardFragment;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = MainActivity.this;
        EventBus.getDefault().register(this);
        closeAndroidPDialog();
        //打开权限
        initView();
        //定位
        getLocationInfo();
        initFragment();
        //添加点击事件
        initListener();

        //得到用户信息
        if (SPUtils.getBoolean(this, "login")) {
            getUserInfo();
        }
        Uri data = getIntent().getData();
        if (null != data) {
            if (TextUtils.isEmpty(data.getQuery())) {
                return;
            }
            String param = data.getQueryParameter("proid");
            if (!TextUtils.isEmpty(param)) {
                startActivity(new Intent(MainActivity.this, ParticularsPageActivity.class)
                        .putExtra("pro_id", param));
            }
        }
        EMClient.getInstance().chatManager().loadAllConversations();
        EMClient.getInstance().addClientListener(clientListener);
        //连接监听
        EMClient.getInstance().addConnectionListener(connectionListener);
        // 获取华为 HMS 推送 token
        HMSPushHelper.getInstance().getHMSToken(this);
        //  EMClient.getInstance().pushManager().getPushConfigs().getDisplayNickname();
        clearSPUtils();
    }

    private void clearSPUtils() {
        Map<String, ?> all = com.hyphenate.easeui.utils.SPUtils.getAll(this);
        for(String key : all.keySet()){
            if (key.contains("friend_id")){
              String  key1 = key;
                Logger.d("EditCreateGroup-----" + key1);
              //  com.hyphenate.easeui.utils.SPUtils.saveConversionJob3(this,key1,false);
                com.hyphenate.easeui.utils.SPUtils.remove(this,key1);
            }
            if (key.contains("gif")){
                String  key2 = key;
                Logger.d("EditCreateGroup-----" + key2);
                com.hyphenate.easeui.utils.SPUtils.remove(this,key2);
                boolean b =  com.hyphenate.easeui.utils.SPUtils.getConversionGif(this,key2);
                Logger.d("EditCreateGroup-----" + key2 + b);
            }
        }
    }

    private void closeAndroidPDialog() {
        try {
            Class aClass = Class.forName("android.content.pm.PackageParser$Package");
            Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
            declaredConstructor.setAccessible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Class cls = Class.forName("android.app.ActivityThread");
            Method declaredMethod = cls.getDeclaredMethod("currentActivityThread");
            declaredMethod.setAccessible(true);
            Object activityThread = declaredMethod.invoke(null);
            Field mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown");
            mHiddenApiWarningShown.setAccessible(true);
            mHiddenApiWarningShown.setBoolean(activityThread, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event != null && event.getMessageKey() != null) {
            if (event.getMessageKey().equals(EventConstants.PUBLISH_DYNAMIC)) {
                // cv_img.setVisibility(View.VISIBLE);
             //   finish();
            } else if (event.getMessageKey().equals(EventConstants.UPDATA_USER_PRODUCT)) {
                getUserInfo();
            }
        }
    }


    private void getUserInfo() {
        Map<String, Object> params = new HashMap<>();
        Map<String, String> params2 = new HashMap<>();
        params2.put("user_id", "");
        params.put("req_bd", params2);
        HttpClient.post(mContext, Constants.QUERYUSERINFO, params, new CallBack<UserBean>() {
            @Override
            public void onSuccess(UserBean resultBean) {
                userBean = resultBean;
                //  tvPost.setText(resultBean.getUser_duties());  //职位
                if (TextUtils.isEmpty(resultBean.user_id)) {
                    return;
                }
                EMClient.getInstance().updateCurrentUserNick(resultBean.getUser_name());
                SPUtils.put(mContext, "user_logo", resultBean.getUser_logo());
                //头像
                SPUtils.saveConversionHeadPhoto(mContext, resultBean.user_id, resultBean.getUser_logo());
                //昵称
                SPUtils.saveConversionNickName(mContext, resultBean.user_id, resultBean.getUser_name());
                //职业
                SPUtils.saveConversionUserDuties(mContext, resultBean.user_id, resultBean.getUser_duties());
                //主业
                SPUtils.saveConversionJob(mContext, resultBean.user_id, resultBean.getUser_job());
                //user_id
                SPUtils.saveConversionUserId(mContext, resultBean.user_id, resultBean.user_id);
                //主业id
                SPUtils.put(mContext, Constants.TYPE_ID, resultBean.type_id);

                SPUtils.put(mContext, Constants.USER_MOBILE, resultBean.user_mobile);
            }
        });
    }


    private void showRed() {
        setBackgroundAlpha((float) 0.4);
        View contentView = LayoutInflater.from(this).inflate(R.layout.popwindow_red_info, null);
        ImageView iv_red = contentView.findViewById(R.id.iv_red);
        ImageView iv_close = contentView.findViewById(R.id.iv_close);
        iv_close.setOnClickListener(v -> mPopWindow.dismiss());

        iv_red.setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, TopUpActivity.class));
            mPopWindow.dismiss();
        });

        mPopWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        View rootView = LayoutInflater.from(this).inflate(R.layout.activity_main, null);
        mPopWindow.showAtLocation(rootView, Gravity.CENTER, 0, 0);
        mPopWindow.setOnDismissListener(() -> setBackgroundAlpha(1));
    }

    private void setBackgroundAlpha(float v) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = v;
        getWindow().setAttributes(lp);
    }

    private void getLocationInfo() {
        mlocationClient = new AMapLocationClient(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mlocationClient.setLocationListener(MainActivity.this);
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        //启动定位
        mlocationClient.startLocation();

        //（仅支持小米、魅族、OPPO、VIVO）
        EMPushHelper.getInstance().setPushListener(new PushListener() {
            @Override
            public void onError(EMPushType pushType, long errorCode) {
                EMLog.e("PushClient", "Push client occur a error: " + pushType + " - " + errorCode);
                // TODO: 开发者会在这个回调中收到使用推送的相关错误信息，各推送类型的error code开发者可以自己去各推送平台官网查询错误原因。
            }

            @Override
            public boolean isSupportPush(EMPushType pushType, EMPushConfig pushConfig) {
                return super.isSupportPush(pushType, pushConfig);
                // TODO：开发者可以复写该方法控制设备是否支持某推送的判断。
            }
        });
    }

    //多设备登录
    EMConnectionListener connectionListener = new EMConnectionListener() {
        @Override
        public void onDisconnected(int error) {
            EMLog.d("global listener", "onDisconnect" + error);
            if (error == EMError.USER_REMOVED) {
                //  onUserException(Constant.ACCOUNT_REMOVED);
                // 显示帐号在其他设备登陆dialog
            } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                UIUtils.showToastSafe("该帐号已在其它设备上登录");
                EMClient.getInstance().logout(true);
                SPUtils.put(MainActivity.this, "welcome", true);
                SPUtils.put(MainActivity.this, "login", false);
                SPUtils.put(MainActivity.mContext, Constants.TOKEN, "");
                // SPUtils.put(context,"login",false);
                Intent intent = new Intent(MainActivity.this, AccountPasswordActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                finish();
            } else if (error == EMError.SERVER_SERVICE_RESTRICTED) {

            }
        }

        @Override
        public void onConnected() { //已连接到服务器


        }
    };


    private void initListener() {
        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.home_button_visitingcard:
                    position = 0;
                    break;
                case R.id.home_button_message:
                    position = 1;
                    break;
              /*  case R.id.home_button_issue:  //发布
                   // position = 2;
                  //  cv_img.setVisibility(View.INVISIBLE);
                    break;*/
                case R.id.home_button_addresslist:
                    position = 2;
                    break;
                case R.id.home_button_my:
                    position = 3;
                    break;
                default:
                    position = 0;
                    break;
            }
            Fragment baseFragment = getFragment(position);
            switchFragment(mContent, baseFragment);
        });
        radioGroup.check(R.id.home_button_visitingcard);
        ll_fabu.setOnClickListener(v -> {
            showFabu();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    // showFabu();
                }
            }, 0);
        });
    }

    private void showFabu() {
        dialog = new Dialog(this, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(this).inflate(R.layout.fragment_issue, null);
        TextView tv_ver = view.findViewById(R.id.tv_ver);
        TextView issue_major = view.findViewById(R.id.issue_major);   //主业
        TextView issue_by_work = view.findViewById(R.id.issue_by_work); //副业
        TextView issue_history = view.findViewById(R.id.issue_history); //副业
        ImageView imageView = view.findViewById(R.id.title_imageview);
        TextView tv_minqin = view.findViewById(R.id.tv_minqin);
        TextView tvTitleName = view.findViewById(R.id.title_textview);
        ImageButton imageButton = view.findViewById(R.id.ib_colse);
        tvTitleName.setText("发布");
        imageView.setVisibility(View.INVISIBLE);
        imageView.setOnClickListener(this);
        issue_major.setOnClickListener(this);
        issue_by_work.setOnClickListener(this);
        issue_history.setOnClickListener(this);
        imageButton.setOnClickListener(this);
        tv_minqin.setOnClickListener(this);
        // dialog.setFocusable(false);
        //点即不消失
        // dialog.setCancelable(false);
        dialog.setContentView(view);
        StatusBarUtil.setTransparent(this);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        Window window = dialog.getWindow();
        if (window == null) {
            return;
        }
        dialog.show();//显示对话框
        // DisplayMetrics dm = new DisplayMetrics();
        // getWindowManager().getDefaultDisplay().getMetrics(dm);
        // WindowManager.LayoutParams lp = window.getAttributes();
        // lp.width = dm.widthPixels;
        // lp.height = dm.heightPixels;

      /*  dialog.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        dialog.getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int visibility) {
                int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                        //布局位于状态栏下方
                        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                        //全屏
                        View.SYSTEM_UI_FLAG_FULLSCREEN |
                        //隐藏导航栏
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
                uiOptions |= 0x00001000;
                dialog.getWindow().getDecorView().setSystemUiVisibility(uiOptions);
            }
        });*/

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        } else {
            dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.white));
        }
        // StatusBarUtil.setTransparent(this);
        //获得window窗口的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        //设置窗口高度为包裹内容
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;

        window.setAttributes(lp);
    }

    private void switchFragment(Fragment fromFragment, Fragment nextFragment) {
        if (mContent != nextFragment) {
            mContent = nextFragment;
            if (nextFragment != null) {
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                //判断nextFrragment是否添加
                if (!nextFragment.isAdded()) {
                    //隐藏当前Fragment
                    if (fromFragment != null) {
                        transaction.hide(fromFragment);
                    }
                    transaction.add(R.id.home_framelayout, nextFragment).commit();
                } else {
                    //隐藏当前fragment
                    if (fromFragment != null) {
                        transaction.hide(fromFragment);
                    }
                    transaction.show(nextFragment).commit();
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //showRed();
        updateUnreadLabel();
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
    }

    @Override
    protected void onPause() {
        super.onPause();
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
        EMClient.getInstance().removeClientListener(clientListener);
    }

    EMClientListener clientListener = new EMClientListener() {
        @Override
        public void onMigrate2x(boolean success) {
            Toast.makeText(MainActivity.this, "onUpgradeFrom 2.x to 3.x " + (success ? "success" : "fail"), Toast.LENGTH_LONG).show();
            if (success) {
                Logger.d("EditCreateGroup-----" + "onMigrate2x");
                refreshUIWithMessage();
            }
        }
    };

    private void updateUnreadLabel() {
        int count = getUnreadMsgCountTotal();
        Logger.d("EditCreateGroup-----" + String.valueOf(count));
        if (count > 0) {
            // badge1.show();
            unread_msg_number.setVisibility(View.VISIBLE);
            unread_msg_number.setText(count + "");
            Bundle extra =new Bundle();
            extra.putString("package", "com.dai.zhenfujin");
            extra.putString("class", "LaunchActivity");
         //   extra.putInt("badgenumber", count);
          //  getContentResolver().call(Uri.parse("content://com.huawei.android.launcher.settings/badge/"), "change_badge", null, extra);

           // setXiaoMiBadge(count);
        } else {
            unread_msg_number.setVisibility(View.INVISIBLE);//影藏显示
        }
    }

    private void setXiaoMiBadge(int count) {
        try {
            Class miuiNotificationClass = Class.forName("android.app.MiuiNotification");
            Object miuiNotification = miuiNotificationClass.newInstance();
            Field field = miuiNotification.getClass().getDeclaredField("messageCount");
            field.setAccessible(true);
            field.set(miuiNotification, String.valueOf(count == 0 ? "" : count));
        } catch (Exception e) {
            e.printStackTrace();
            // miui6之前
            Intent localIntent = new Intent("android.intent.action.APPLICATION_MESSAGE_UPDATE");
            localIntent.putExtra("android.intent.extra.update_application_component_name", getPackageName() + "/." + "MainActivity");
            localIntent.putExtra("android.intent.extra.update_application_message_text", String.valueOf(count == 0 ? "" : count));
            sendBroadcast(localIntent);
        }
    }


    EMMessageListener messageListener = new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            // notify new message
            Logger.d("EditCreateGroup-----" + "onMessageReceived2----MainActivity");
            for (EMMessage message : messages) {
                //  DemoHelper.getInstance().getNotifier().vibrateAndPlayTone(message);
            }
            refreshUIWithMessage();
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            Logger.d("EditCreateGroup-----" + "onCmdMessageReceived----MainActivity");
            for (EMMessage messageCmd : messages) {
                final EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) messageCmd.getBody();
                Logger.d("MessageFragment------EditCreateGroup-----" + cmdMsgBody.action() + "----MessageFragment");
                if (cmdMsgBody.action().equals(PUBLISH_DYNAMIC)) {  //动态提醒
                    // runOnUiThread(() -> cv_img.setVisibility(View.VISIBLE));
                }
                // MessageEvent messageEvent = new MessageEvent();
                //  messageEvent.setMessageKey(EventConstants.UPDATA_FANS_LIST);
                //  EventBus.getDefault().post(messageEvent);
            }

            refreshUIWithMessage();
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
        }

        //收到消息
        @Override
        public void onMessageRecalled(List<EMMessage> messages) {
            refreshUIWithMessage();
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
        }
    };

    private void refreshUIWithMessage() {
        runOnUiThread(new Runnable() {
            public void run() {
                updateUnreadLabel();
            }
        });
    }


    private Fragment getFragment(int position) {
        if (baseFragments != null && baseFragments.size() > 0) {
            Fragment baseFragment = baseFragments.get(position);
            return baseFragment;
        }
        return null;
    }

    //未读的消息
    private int getUnreadMsgCountTotal() {
        // return EMClient.getInstance().chatManager().getConversation(SPUtil.getString(Constants.USERID)).getUnreadMsgCount();
        return EMClient.getInstance().chatManager().getUnreadMessageCount();
    }

    private void initFragment() {
      //  visitingcardFragment = ;
      //  String showRed = getIntent().getStringExtra("showRed");
       // int showRed = getIntent().getExtras().getInt("showRed");
      //  Bundle bundle = getIntent().getExtras();
      //  bundle.putInt("showRed",0);
     //   visitingcardFragment.setArguments(getIntent().getExtras());

        baseFragments = new ArrayList<>();
        baseFragments.add(new VisitingcardFragment());//名片  //ConversationListFragment
        baseFragments.add(new ConversationListFragment());//消息
        //   baseFragments.add(new IssueFragment2());//发布  //IssueFragment2
        baseFragments.add(new AddressListFragment());//通讯录
        baseFragments.add(new MyFragment());//我的
    }

    private void initView() {
        frameLayout = findViewById(R.id.home_framelayout);
        radioGroup = findViewById(R.id.home_radiogroup);
        cv_img = findViewById(R.id.cv_img);
        unread_msg_number = findViewById(R.id.unread_msg_number);

        button2 = (Button) findViewById(R.id.btn_msg);
        ll_fabu = findViewById(R.id.ll_fabu);
        //  remind(button2);

        RxPermissions rxPermissions = new RxPermissions(MainActivity.this);
        rxPermissions
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
                        , Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION
                        , Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.READ_PHONE_STATE
                        , Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO
                        , Manifest.permission.READ_PHONE_STATE)
                .subscribe(granted -> {
                    if (granted) {
                        //  Toast.makeText(MainActivity.this, "同意权限", Toast.LENGTH_SHORT).show();
                    } else {
                        //  Toast.makeText(MainActivity.this, "拒绝权限", Toast.LENGTH_SHORT).show();
                    }
                });
    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                latitude = aMapLocation.getLatitude();
                longitude = aMapLocation.getLongitude();
                city = aMapLocation.getCity();
                SPUtils.put(this, "latitude", latitude);
                SPUtils.put(this, "longitude", longitude);
                SPUtils.put(this, "city", city);
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        if(dialog != null) {
            dialog.dismiss();
        }
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View v) {
        String userId = SPUtils.getString(mContext, Constants.USER_MOBILE);
        switch (v.getId()) {
            case R.id.issue_major://主业
                if (!SPUtils.getBoolean(this, "login")) {  //登录为true
                    Intent intent = new Intent(this, AccountPasswordActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    SPUtils.put(MainActivity.mContext, Constants.TOKEN, "");
                    startActivity(intent);
                    return;
                }
                if (TextUtils.isEmpty(SPUtils.getConversionUserJob(this, userId))) {
                    new CommonDialog(this, R.style.dialog, false, "发布产品前需先发布名片", (dialog, confirm) -> {
                        if (confirm) { //truethis
                            startActivity(new Intent(this, ReleaseActivity.class));
                        } else {

                        }
                        dialog.dismiss();
                    }).show();
                    return;
                }
                Intent room = new Intent(this, AlumIssueActivity2.class);
                room.putExtra("type", 3);
                startActivity(room);
                dialog.dismiss();
                break;
            case R.id.issue_by_work://副
                /*if (TextUtils.isEmpty(SPUtils.getConversionUserJob(this, userId))) {
                    //  getUserInfo();
                    startActivity(new Intent(this, ReleaseActivity.class));
                    UIUtils.showToastSafe("请先完善名片信息");
                    return;
                }*/

                if (!SPUtils.getBoolean(this, "login")) {  //登录为true
                    Intent intent = new Intent(this, AccountPasswordActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    SPUtils.put(MainActivity.mContext, Constants.TOKEN, "");
                    startActivity(intent);
                    return;
                }
                if (TextUtils.isEmpty(SPUtils.getConversionUserJob(this, userId))) {
                    new CommonDialog(this, R.style.dialog, false, "发布产品前需先发布名片", (dialog, confirm) -> {
                        if (confirm) { //truethis
                            startActivity(new Intent(this, ReleaseActivity.class));
                        } else {

                        }
                        dialog.dismiss();
                    }).show();
                    return;
                }
                Intent vehicle = new Intent(this, AlumTypeActivity.class);
                vehicle.putExtra("type", 2);
                startActivity(vehicle);
                dialog.dismiss();
                break;
            case R.id.issue_history://历史记录
                Intent intent = new Intent(this, MyActivity.class);
                startActivity(intent);
                dialog.dismiss();
                break;
            case R.id.tv_minqin://名片
                Intent intent2 = new Intent(this, ReleaseActivity.class);
                intent2.putExtra("userBean", MainActivity.userBean);
                startActivity(intent2);
                dialog.dismiss();
                break;
            case R.id.ib_colse://名片
                dialog.dismiss();
                break;
        }
    }
}
